import { addTrackMonitors, deleteMonitorsRollCall, deleteTrackMonitors, getMonitorsTrackList, updateMonitorsRollCall } from '@/api/monitors'
import { getPublishPlatformMap } from '@/hooks/usePublishMap'
import { getMapTree } from '@hs-admin/api'
import { message } from '@hs-admin/utils'
import { Button, Cascader, Flex, Modal } from 'antd'
import { SetStateAction, useRef, useState } from 'react'
import { monitorsList, addmonitorsList } from '@/api/home'
import { CheckCircleOutlined, CloseCircleOutlined, DeleteOutlined, EditOutlined, UpOutlined } from '@ant-design/icons'
import './style.less'
import { HsAdminInput } from '@hs-admin/base-components'
import { AreaTreeSelect } from '@hs-server/components'

interface TrackProps {
  success: () => void
}
export const useAddTrack = (props: TrackProps) => {
  const { success } = props
  const [open, setOpen] = useState(false)
  const [hasSelectedTrackList, sethasSelectedTrackList] = useState<any[]>([])
  const [publishTrackList, setpublishTrackList] = useState<any[]>([])
  const [activeTrackRow, setactiveTrackRow] = useState([])
  const monitorsRegion = useRef<any[]>([])
  const [publishTrackValue, setpublishTrackValue] = useState([])
  const [areaValue, setareaValue] = useState(null)

  const handleShowArea = (item: { node_name?: any; node_id?: any; region: any; count?: number }) => {
    return item.region ? item.region.split('-').at(-1)?.split('|')[0] : '全国'
  }
  const handlePublishMapData = (unique: any[]) => {
    const treeList = unique.map((first: any) => ({
      label: first.node_name,
      value: first.id,
      industry_domain: first.industry_domain,
      map_id: first.map_id
    }))
    return treeList
  }
  const getMapChildren = (treeList: any[]) => {
    treeList.forEach(async (item: { map_id: any; children: any[]; node_name: string; node_code: string }) => {
      await getMapTree({ id: item.map_id }).then((res: any) => {
        if (res.length) {
          item.node_name = res[0].node_name
          item.node_code = res[0].node_code
        }
      })
    })
  }
  const callList = () => {
    return getMonitorsTrackList({}).then((res) => {
      sethasSelectedTrackList(res.items ?? [])
      setOpen(true)
    })
  }

  return {
    AddTrackModal: (
      <Modal
        title="赛道监测"
        open={open}
        width="30vw"
        onCancel={() => {
          sethasSelectedTrackList([])
          setpublishTrackList([])
          setpublishTrackValue([])
          setactiveTrackRow([])
          setareaValue(null)
          setOpen(false)
        }}
        onOk={() => {
          if (!activeTrackRow.length) {
            message.warning('请选择赛道')
            return
          }
          const nodeItem: any = activeTrackRow.at(-1)
          const params = {
            map_id: `${nodeItem.map_id}`,
            map_name: nodeItem.label,
            node_id: nodeItem.node_code,
            node_level: 1,
            node_name: nodeItem.node_name,
            region: monitorsRegion.current.length
              ? monitorsRegion.current.map((item: { label: any; value: any }) => `${item.label}|${item.value}`).join('-')
              : '',
            released_map_id: nodeItem.value
          }
          addTrackMonitors(params).then(() => {
            success()
            message.success('新增赛道监测成功')
            sethasSelectedTrackList([])
            setpublishTrackList([])
            setpublishTrackValue([])
            setactiveTrackRow([])
            setareaValue(null)
            setOpen(false)
          })
        }}>
        <Flex align="center" gap={'small'} justify="space-between">
          <Flex align="center" gap={'small'}>
            <img className="w-14px" src="/static/img/Monitors/赛道监测.png" alt="" />
            <p>赛道监测</p>
          </Flex>
          <UpOutlined className="mr-2" />
        </Flex>
        <div className="h-300px overflow-auto">
          {hasSelectedTrackList.map((item, index) => (
            <Flex align="center" gap={'small'} key={index} className="mt-4 track-list-item" justify="space-between">
              <div className="leading-16px w-40 ml-6">
                {item.node_name}
                <p className="leading-14px text-#999999 text-12px">{handleShowArea(item)}</p>
              </div>
              <Flex align="center" gap={'small'}>
                <DeleteOutlined
                  className="cursor-pointer"
                  onClick={() => {
                    deleteTrackMonitors({ id: item.id }).then(() => {
                      message.success('删除成功')
                      success()
                      callList()
                    })
                  }}
                />
                <p className="mr-2 text-#595959">{item.count}家</p>
              </Flex>
            </Flex>
          ))}
        </div>
        <br />
        <br />
        <Flex align="center" gap={'middle'}>
          <p className="w-60px flex-none">赛道</p>
          <Cascader
            value={publishTrackValue}
            showSearch={true}
            options={publishTrackList}
            onChange={(value: any, row: any) => {
              setactiveTrackRow(row)
              setpublishTrackValue(value)
            }}
            placeholder="请选择赛道"
            className="w-112"
          />
        </Flex>
        <Flex align="center" gap={'middle'} className="my-2">
          <p className="w-60px flex-none">区域选择</p>
          <AreaTreeSelect
            value={areaValue}
            onChange={(value: any, label: string) => {
              const arr: any = []
              if (value) {
                const obj: any = {
                  value,
                  show: label[0]
                }
                arr.push(obj)
              }
              setareaValue(value)
            }}
            onSelect={(_value: any, node: { parent: any; label: any; value: any }) => {
              if (node.parent) {
                monitorsRegion.current = [...node.parent, { label: node.label, value: node.value }]
              } else {
                monitorsRegion.current = [{ label: node.label, value: node.value }]
              }
            }}
            placeholder="请选择区域"
            className="w-112"
          />
        </Flex>
      </Modal>
    ),
    doOpenTrack: () => {
      callList()
      const p1 = getPublishPlatformMap('生物医药专区').then((unique) => {
        const treeList = handlePublishMapData(unique)
        getMapChildren(treeList)
        return treeList
      })
      const p2 = getPublishPlatformMap('新能源专区').then((unique) => {
        const treeList = handlePublishMapData(unique)
        getMapChildren(treeList)
        return treeList
      })
      const p3 = getPublishPlatformMap('汽车专区').then((unique) => {
        const treeList = handlePublishMapData(unique)
        getMapChildren(treeList)
        return treeList
      })
      const p4 = getPublishPlatformMap('新材料专区').then((unique) => {
        const treeList = handlePublishMapData(unique)
        getMapChildren(treeList)
        return treeList
      })
      const p5 = getPublishPlatformMap('未来产业专区').then((unique) => {
        const treeList = handlePublishMapData(unique)
        getMapChildren(treeList)
        return treeList
      })
      Promise.allSettled([p1, p2, p3, p4, p5]).then((res: any[]) => {
        setpublishTrackList([
          {
            label: '生物医药产业',
            value: '生物医药产业',
            children: res[0].value
          },
          {
            label: '新能源产业',
            value: '新能源产业',
            children: res[1].value
          },
          {
            label: '汽车产业',
            value: '汽车产业',
            children: res[2].value
          },
          {
            label: '新材料产业',
            value: '新材料产业',
            children: res[3].value
          },
          {
            label: '未来产业',
            value: '未来产业',
            children: res[4].value
          }
        ])
      })
    }
  }
}

export const useAddCompany = (props: TrackProps) => {
  const { success } = props
  const [open, setOpen] = useState(false)
  const [hasSelectedCompanyList, sethasSelectedCompanyList] = useState<any[]>([])
  const [selectedName, setselectedName] = useState('')

  const addList = (value: string) => {
    if (!value) {
      message.warning('请输入新增名单名称')
      return
    }
    setselectedName(value)
    addmonitorsList({ name: value }).then(() => {
      message.success('添加监测成功')
      success()
      sethasSelectedCompanyList([])
      setselectedName('')
      setOpen(false)
    })
  }
  const updateList = (value: string, item: any) => {
    updateMonitorsRollCall({ id: item.id, name: value }).then(() => {
      message.success('更新监测成功')
      success()
      callList()
    })
  }

  const callList = () => {
    return monitorsList({ page: 1, page_size: 199 }).then((res) => {
      sethasSelectedCompanyList(res.items ?? [])
      return res
    })
  }

  return {
    AddCompanyModal: (
      <Modal
        title="企业监测名单"
        open={open}
        width="30vw"
        footer={null}
        onCancel={() => {
          sethasSelectedCompanyList([])
          setselectedName('')
          setOpen(false)
        }}>
        <Flex align="center" gap={'small'} justify="space-between">
          <Flex align="center" gap={'small'}>
            <img className="w-14px" src="/static/img/Monitors/企业名单监测.png" alt="" />
            <p>企业名单监测</p>
          </Flex>
          <UpOutlined className="mr-2" />
        </Flex>
        {hasSelectedCompanyList.map((item, index) => (
          <Flex align="center" gap={'small'} key={index} className="track-list-item" justify="space-between">
            {item.edit && (
              <Flex align="center" gap={'small'} className="w-8/10">
                <HsAdminInput
                  value={item.name}
                  placeholder="输入名称"
                  className="w-8/10"
                  allowClear
                  onChange={(e: { target: { value: any } }) => {
                    item.name = e.target.value
                    sethasSelectedCompanyList([...hasSelectedCompanyList])
                  }}
                  onPressEnter={(e: { target: { value: any } }) => updateList(e.target.value, item)}
                />
                <CloseCircleOutlined
                  className="cursor-pointer"
                  onClick={() => {
                    callList()
                  }}
                />
                <CheckCircleOutlined
                  className="cursor-pointer"
                  onClick={() => {
                    updateList(item.name, item)
                  }}
                />
              </Flex>
            )}
            {!item.edit && <div className="leading-16px w-60 ml-5">{item.name}</div>}
            <Flex align="center" gap={'small'}>
              <EditOutlined
                className="cursor-pointer"
                onClick={() => {
                  item.edit = true
                  sethasSelectedCompanyList([...hasSelectedCompanyList])
                }}
              />
              <DeleteOutlined
                className="cursor-pointer"
                onClick={() => {
                  deleteMonitorsRollCall({ id: item.id }).then(() => {
                    message.success('删除成功')
                    success()
                    callList()
                  })
                }}
              />
              <p className="mr-2 text-#595959">{item.count}家</p>
            </Flex>
          </Flex>
        ))}
        <br />
        <br />
        <Flex align="center" gap={'small'}>
          <HsAdminInput
            value={selectedName}
            placeholder="输入新增名单名称"
            className="w-full"
            onChange={(e: { target: { value: SetStateAction<string> } }) => setselectedName(e.target.value)}
            onPressEnter={(e: { target: { value: any } }) => addList(e.target.value)}
            allowClear
          />
          <Button type="primary" onClick={() => addList(selectedName)}>
            确定
          </Button>
        </Flex>
      </Modal>
    ),
    doOpenCompany: () => {
      callList().then(() => {
        setOpen(true)
      })
    }
  }
}
